package com.welike.shibo.controller.v2.api;

import com.alibaba.fastjson.JSONObject;
import com.welike.shibo.aspect.annotation.AutoLog;
import com.welike.shibo.eneity.JsonResult;
import com.welike.shibo.enums.ResultEnum;
import com.welike.shibo.service.SysUserService;
import com.welike.shibo.utils.ResultUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2019/11/20 5:31 下午
 */
@Slf4j
@Api(value = "权限相关接口")
@RestController
@RequestMapping("/v2/auth")
public class AuthController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(operateState = "登录")
    @PostMapping("/login")
    public JsonResult login(@RequestBody JSONObject jsonObject) {
        log.info("/login");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
            return ResultUtils.success("登录成功");
        } catch (UnknownAccountException e) {
            log.error("e ==> {}", e.getMessage());
            return ResultUtils.error(404, e.getMessage());
        } catch (IncorrectCredentialsException e) {
            log.error("e ==> {}", e.getMessage());
            return ResultUtils.error("账号或密码不匹配");
        } catch (LockedAccountException e) {
            log.error("e ==> {}", e.getMessage());
            return ResultUtils.error("账号被锁定");
        } catch (AuthenticationException e) {
            log.error("e ==> {}", e.getMessage());
            return ResultUtils.error("密码错误");
        } catch (Exception e) {
            log.error("e ==> {}", e.getMessage());
            return ResultUtils.error("登录失败" + e.getMessage());
        }
    }

    /**
     * 查询当前登录用户的信息
     */
    @AutoLog
    @PostMapping("/getInfo")
    public JsonResult getInfo() {
        try {
            return sysUserService.getInfo();
        } catch (Exception e){
            log.info(e.getMessage());
            return ResultUtils.error(ResultEnum.E_20011);
        }
    }

    /**
     * 登出
     */
    @AutoLog(operateState = "登出")
    @PostMapping("/logout")
    public JsonResult logout() {
        return sysUserService.logout();
    }


}
